import { Button, Popconfirm, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import React, { useEffect, useRef, useState } from 'react';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { allInfoSpot, allPanorama, delInfoSpot, infoSpotCreate, infoSpotList, infoSpotUpdate } from '../service';
import type { PanoramaItem, PanoramaPagination } from '../panorama/data';
import { commonStatus } from '@/constant/constant';
import ProForm, { ProFormText, ProFormSelect, ModalForm, ProFormDependency } from '@ant-design/pro-form';
import Panolens from '@/components/Panolens';
import VideoUpload from '@/components/VideoUpload';
import { InfoSpotItem } from '../infospot/data';
import IconRadio from './iconRadio';

// 场景map
// let panoramaMap = {}




/**∂
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields: InfoSpotItem) => {
    const hide = message.loading('正在添加');
    if (fields?.video) {
        fields.video = fields?.video.map((item: any) => item.url)
    }
    try {
        await infoSpotCreate({ ...fields });
        hide();
        message.success('添加成功');
        return true;
    } catch (error) {
        hide();
        message.error('添加失败请重试！');
        return false;
    }
};


/**
* 更新节点
*
* @param fields
*/
const handleUpdate = async (fields: any, currentRow?: InfoSpotItem) => {
    const hide = message.loading('正在修改');
    if (fields?.video) {
        fields.video = fields?.video.map((item: any) => item.url)
    }
    try {
        await infoSpotUpdate({
            guid: currentRow?.guid,
            ...fields,
        });
        hide();
        message.success('修改成功');
        return true;
    } catch (error) {
        hide();
        message.error('修改失败');
        return false;
    }
};

const InfoSpotList: React.FC<{ panorama?: string, }> = ({ panorama }) => {
    const actionRef = useRef<ActionType>();
    const [panoramaMap, setPanoramaMap] = useState<{ [key: string]: PanoramaItem }>({});
    /** 新建窗口的弹窗 */
    const [createModalVisible, handleModalVisible] = useState<boolean>(false);
    const [panoramaData, setPanoramaData] = useState<PanoramaItem[]>([]);
    const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
    const [currentRow, setCurrentRow] = useState<InfoSpotItem>();
    const [canPanoramaData, setCanPanoramaData] = useState<any[]>([]);
    const [oldInfoSpot, setOldInfoSpot] = useState<any[]>([]);
    // 修改表格Ref
    const formRef = useRef<any>();
    // 添加表格Ref
    const formAddRef = useRef<any>();


    function updateStatus(guid: string, status: number) {
        infoSpotUpdate({
            guid,
            status
        }).then(() => {
            message.success('更改成功')
            actionRef?.current?.reload()
        }
        )
    }
    async function getAllPanoramaData() {
        let data: PanoramaItem[] = await allPanorama({ status: 1 })
        let map = {}
        data.forEach((element) => {
            map[element.guid] = element
        });
        setPanoramaData(data)
        console.log(map);

        setPanoramaMap(map)
        if (panorama) {
            getCanPanoramaData(map[panorama || '']?.map_id, panorama, undefined, data)
        }
    }

    useEffect(() => {
        getAllPanoramaData()
    }, [])


    /**
     * 获取可以到达的景点
     * @param map_id 
     * @param panorama_id 
     * @param keyWords 
     */
    async function getCanPanoramaData(map_id?: string, panorama_id?: string, keyWords?: string, arrPanorama?: PanoramaItem[]) {
        let data = panoramaData
        if (arrPanorama) {
            data = arrPanorama
        }
        data = data.filter((item: PanoramaItem) => item.guid !== panorama_id && item.map_id == map_id)
        if (keyWords) {
            data = data.filter((item: PanoramaItem) => item.name.includes(keyWords))
        }
        let res = data.map((item: PanoramaItem) => {
            return {
                value: item.guid,
                label: item.name
            }
        })
        setCanPanoramaData(res)
    }


    async function getPanoramaOldInfoSpot(id: string) {
        // handleLoading(true)
        message.loading('正在加载')
        let data = await allInfoSpot({ panorama_id: id })
        console.log(data);

        setOldInfoSpot(data)
        message.destroy()
    }





    const columns: ProColumns<InfoSpotItem>[] = [
        {
            title: '信息点编号',
            dataIndex: 'guid',
            ellipsis: true,
            copyable: true,
        },
        {
            title: '信息点名称',
            dataIndex: 'name',

        },
        {
            title: '所属场景',
            dataIndex: 'panorama_id',
            fieldProps: {
                fieldNames: { label: 'name', value: 'guid' },
                options: panoramaData,
            },
            valueType: 'select',
        },
        {
            title: '直角坐标',
            dataIndex: 'coordinates',
            search: false,
            renderText: (renderText) => `X:${renderText[0]} Y:${renderText[1]} Z:${renderText[2]}`
        },
        {
            title: '可到达场景',
            search: false,
            dataIndex: 'to_panorama_id',
            fieldProps: {
                fieldNames: { label: 'name', value: 'guid' },
                options: panoramaData,
            },
            valueType: 'select',
        },
        {
            title: '视频地址',
            dataIndex: 'video',
            search: false,
            renderText: (renderText) => renderText && Array.isArray(renderText) && renderText.length > 0 ? typeof renderText[0] == 'object' ? renderText[0]['url'] : `${renderText[0]}` : '-'
        },
        {
            title: '状态',
            dataIndex: 'status',
            hideInForm: true,
            valueEnum: commonStatus,
        },
        {
            title: '创建时间',
            dataIndex: 'created_at',
            search: false,
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => [

                <a
                    key="update"
                    // @ts-ignore
                    // disabled={record.status != 2}
                    onClick={async () => {
                        // if (record.status != 2) {
                        //     return
                        // }
                        setCurrentRow(record);

                        if (record?.video && Array.isArray(record.video)) {

                            record.video = record.video.map((item: string, index: number) => {
                                if (typeof item === 'object') {
                                    return item
                                }
                                return {
                                    uid: index,
                                    name: item.split('__')[1],
                                    url: item,
                                    status: 'done'
                                }
                            })
                        }
                        let item = panoramaMap[record.panorama_id]

                        await getCanPanoramaData(item.map_id, item.guid, '')
                        await getPanoramaOldInfoSpot(item.guid)
                        handleUpdateModalVisible(true);
                    }}
                >
                    {' '}
                    编辑{' '}
                </a>,
                record.status != 1 ? [
                    <Popconfirm
                        key="confirm"
                        title="是否确认启动该项目?"
                        onConfirm={() => {
                            updateStatus(record.guid, 1)
                        }}
                        okText="是"
                        cancelText="否"
                    >
                        <a type="link" key="confirm">启动</a>
                    </Popconfirm>,
                    <Popconfirm
                        key="del"
                        title="是否确认删除?"
                        onConfirm={() => {
                            delInfoSpot({
                                guid: record.guid,
                            }).then(() => {
                                message.success('删除成功')
                                actionRef?.current?.reload()
                            }
                            )
                        }}
                        okText="是"
                        cancelText="否"
                    >
                        <a type="link" key="del" style={{ color: 'red' }}>删除</a>
                    </Popconfirm>
                ]
                    :
                    <Popconfirm
                        key="close"
                        title="是否确认关闭该项目?"
                        onConfirm={() => {
                            updateStatus(record.guid, 2)
                        }}
                        okText="是"
                        cancelText="否"
                    >
                        <a type="link" key="close">关闭</a>
                    </Popconfirm>,

            ],
        },
    ];
    // 修改或添加表单 name role avatar 
    const EditBox = (ref: any) => (<>
        <ProFormText
            rules={[
                {
                    required: true,
                },
            ]}
            width="md"
            name="name"
            label="信息点名称"
        />
        <ProFormSelect
            name="panorama_id"
            label="所属场景"
            showSearch
            width="md"
            debounceTime={300}
            request={async ({ keyWords }) => {
                try {
                    let data = await allPanorama({ name: keyWords, status: 1 })

                    let res = data.map((item: { guid: string, name: string, url: string }) => {

                        return {
                            value: item.guid,
                            label: item.name
                        }
                    })

                    return res

                } catch (error) {
                    return []
                }

            }}
            placeholder="请选择所属场景,输入可搜索"
            rules={[{ required: true, message: '请选择所属场景' }]}
            fieldProps={{
                onChange: (value) => {
                    getPanoramaOldInfoSpot(value)
                    // 类型改变后初始化数据源
                    ref?.current?.setFieldsValue({
                        to_panorama_id: undefined,
                        coordinates: undefined,
                    });
                    let item = panoramaMap[value]
                    getCanPanoramaData(item.map_id, value, '')
                    getPanoramaOldInfoSpot(value)
                    ref.current?.resetFields(['coordinates'])
                }
            }}
        />

        <ProFormDependency name={['panorama_id']}>
            {({ panorama_id }) => {

                if (panorama_id) {
                    let item = panoramaMap[panorama_id]

                    if (!item) {
                        return null
                    }
                    return <div>
                        <ProForm.Item
                            name="coordinates"
                            label="信息点坐标"
                            rules={[
                                {
                                    required: true,
                                },
                            ]}>
                            <Panolens url={item.url} infoSpot={oldInfoSpot} container={'container'} />
                        </ProForm.Item>
                        <ProFormSelect
                            name="to_panorama_id"
                            label="信息点可到达场景"
                            showSearch
                            width="md"
                            debounceTime={300}
                            options={canPanoramaData}
                            placeholder="请选择可到达场景,输入可搜索"
                            fieldProps={{
                                onSearch(value) {
                                    getCanPanoramaData(item.map_id, panorama_id, value)
                                },
                            }}
                        />
                        <ProFormDependency name={['to_panorama_id']}>
                            {({ to_panorama_id }) => {

                                if (to_panorama_id) {


                                    return <div>
                                        <ProForm.Item
                                            name="camera_coordinates"
                                            label="通过该点到场景时相机初始视角"
                                        >
                                            <Panolens type={2} url={panoramaMap[to_panorama_id].url} infoSpot={[]} container={'container1'} />
                                        </ProForm.Item>
                                        <IconRadio label='信息点图标' name='icon' value={currentRow?.icon || panoramaMap[to_panorama_id].icon} form={ref}></IconRadio>
                                    </div>
                                }


                                return null;
                            }}
                        </ProFormDependency>
                    </div>
                }


                return null;
            }}
        </ProFormDependency >
        <ProFormDependency name={['to_panorama_id']}>
            {({ to_panorama_id }) => {

                if (to_panorama_id) {
                    return <VideoUpload name='video' label='进入下一个场景前播放的视频'></VideoUpload>
                }


                return null;
            }}
        </ProFormDependency>

    </>)

    return (
        <>
            <ProTable<InfoSpotItem, PanoramaPagination>
                headerTitle="查询表格"
                actionRef={actionRef}
                rowKey="guid"
                search={{
                    labelWidth: 120,
                }}
                pagination={{
                    pageSize: 10,
                    showSizeChanger: true
                }}
                toolBarRender={() => [
                    <Button
                        key="detail"
                        type="primary"
                        onClick={() => {
                            handleModalVisible(true);
                        }}
                    >
                        {' '}
                        <PlusOutlined /> 创建{' '}
                    </Button>,
                ]}
                request={async (params, sort, filter) => {
                    return infoSpotList(Object.assign({ panorama_id: panorama }, params));
                }}
                columns={columns}
            />
            {/* 新建modal */}
            <ModalForm
                title="新建"
                width="600px"
                visible={createModalVisible}
                formRef={formAddRef}
                onVisibleChange={handleModalVisible}
                modalProps={{
                    destroyOnClose: true
                }}
                initialValues={{
                    panorama_id: panorama
                }}

                onFinish={async (value) => {

                    const success = await handleAdd({ ...value } as InfoSpotItem);
                    if (success) {
                        handleModalVisible(false);
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
            >

                {/* 与编辑组件重复抽离 */}
                {EditBox(formAddRef)}

            </ModalForm>
            {/* 编辑 */}
            <ModalForm
                title="编辑"
                width="600px"
                visible={updateModalVisible}
                formRef={formRef}
                onVisibleChange={handleUpdateModalVisible}
                modalProps={{
                    destroyOnClose: true
                }}
                initialValues={{
                    ...currentRow,
                }}

                onFinish={async (value) => {
                    const success = await handleUpdate(value, currentRow);
                    if (success) {
                        handleUpdateModalVisible(false);
                        setCurrentRow(undefined);
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
            >
                {EditBox(formRef)}

            </ModalForm>
        </>
    );
};

export default InfoSpotList;
